<template>
  <el-dialog v-model="dialogVisible" :title="addressForm.id ? '编辑地址' : '新增地址'" width="50%">
    <el-form ref="formRef" :model="addressForm" :rules="rules" label-width="100px" style="padding-right: 30px">
      <el-form-item label="收货人：" prop="receiver">
        <el-input v-model="addressForm.receiver" placeholder="请输入收货人"></el-input>
      </el-form-item>
      <el-form-item label="联系方式：" prop="contact">
        <el-input v-model="addressForm.contact" placeholder="请输入联系方式"></el-input>
      </el-form-item>
      <el-form-item label="收货地址：" prop="address">
        <AddressSelect ref="addressSelectRef" v-model="addressForm.address" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { nextTick } from 'vue';
import { createAddressAPI, editAddressAPI } from "@/apis/address";
import AddressSelect from "./AddressSelect.vue";

// 状态和引用定义
const dialogVisible = ref(false);
const formRef = ref(null);
const addressSelectRef = ref(null);
const addressForm = ref({
  receiver: "",
  contact: "",
  address: "",
});

// 表单验证规则
const rules = {
  receiver: [
    { required: true, message: "收货人不能为空", trigger: "blur" },
    { min: 2, max: 10, message: "收货人为2-10个字符", trigger: "blur" },
  ],
  contact: [
    { required: true, message: "联系方式不能为空", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的手机号码",
      trigger: "blur",
    },
  ],
  address: [
    { required: true, message: "地址不能为空", trigger: "blur" },
    { min: 15, max: 50, message: "地址为15-50个字符", trigger: "blur" },
  ],
};

// 打开弹窗
const open = async (row) => {
  dialogVisible.value = true;
  addressForm.value = { ...row };
  await nextTick();
  if (row.address) {
    addressSelectRef.value.parseAddress(row.address);
  }
};

// 事件定义
const emit = defineEmits(["success"]);

// 提交表单
const onSubmit = async () => {
  await formRef.value.validate();
  const isEdit = addressForm.value.id;
  if (isEdit) {
    await editAddressAPI(addressForm.value);
    ElMessage.success("编辑成功");
  } else {
    await createAddressAPI(addressForm.value);
    ElMessage.success("添加成功");
  }
  dialogVisible.value = false;
  emit("success");
};

// 暴露 open 方法供父组件调用
defineExpose({
  open,
});
</script>